package com.hbsoft.util;

import com.hb.util.HttpUtil;
import com.hbsoft.config.SysConfigInfo;
import com.hbsoft.lms.vo.Action_info;
import com.hbsoft.lms.vo.QrCode;
import com.hbsoft.lms.vo.Scene;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Map;

@Service
public class WechatUtil {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysConfigInfo sysConfigInfo;

    private final static String getQrCodeUrl = "http://10.199.224.21:9006/wx/cgi-bin/qrcode/create?access_token=TOKEN";


    public String getAccessToken() {
        String url = sysConfigInfo.getWxTokenInterfacePath();
        String params = "Mode=getAccessToken()";
        String token = HttpUtil.sendJSONPost(url, params);
        logger.info("获取token，入参：{},出参：{}",params,token);
        return token;
    }

    /**
     * 公众号二维码
     * @return
     */
    public Map<String,Object> getQrCode(String qrParam){
        QrCode param  = new QrCode();
        Scene scene = new Scene();
        scene.setScene_str(qrParam);
        Action_info ai = new Action_info();
        ai.setScene(scene);
        param.setAction_name("QR_LIMIT_STR_SCENE");
        param.setAction_info(ai);
        String url = getQrCodeUrl.replace("TOKEN",getAccessToken());
        String paramJson = GsonUtil.toJson(param);
        String result = HttpUtil.sendJSONPost(url,paramJson);
        logger.info("获取二维码参数：{},返回结果:{}",paramJson,result);
        Map<String,Object> map = GsonUtil.fromJson(result,Map.class);
        return map;
    }

    public Boolean sendJSONPostReturnInputStrem(String url, String jsonParam, String path, Map<String, String> headerInfo, String charSet,
                                              int timeOut, int socketTimeout) {
        String strResult = null;
        CloseableHttpClient httpCilent = null;
        HttpGet httpPost = null;
        RequestConfig requestConfig = null;
        CloseableHttpResponse response = null;
        StringEntity entity = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (jsonParam != null && !jsonParam.isEmpty()) {
                entity = new StringEntity(jsonParam, charSet);
            }
            httpCilent = HttpClients.createDefault();
            httpPost = new HttpGet(url);

            requestConfig = RequestConfig.custom()//
                    .setConnectionRequestTimeout(timeOut)// 设置请求连接超时时间
                    .setConnectTimeout(timeOut)// 设置连接超时时间
                    .setSocketTimeout(socketTimeout)// 数据传输过程中数据包之间间隔的最大时间
                    .build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader(new BasicHeader("Content-Type", "application/json;charset=" + charSet));
            // httpPost.setHeader(new BasicHeader("Accept",
            // "text/plain;charset=" + charSet));
            httpPost.setHeader(new BasicHeader("Accept", "application/json;charset=" + charSet));
            if (headerInfo != null && !headerInfo.isEmpty()) {
                for (String key : headerInfo.keySet()) {
                    httpPost.setHeader(new BasicHeader(key, headerInfo.get(key)));
                }
            }
            response = httpCilent.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            switch (statusCode) {
                case HttpStatus.SC_OK:
                    HttpEntity httpEntity=response.getEntity();
                    inputStream=httpEntity.getContent();
                    break;
                case HttpStatus.SC_NOT_FOUND:
                    System.out.println("POST请求404未找到信息");
                    break;
                case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                    System.out.println("POST请求500请求地址发生异常");
                    break;
                default:
                    System.out.println("POST请求错误状态码:" + statusCode);
                    break;
            }
            File file = new File(path);
            // 假如目标路径不存在,则新建该路径
            if (!file.getParentFile().exists()) {
                logger.info("合成后图片目标路径不存在,新建该路径");
                file.getParentFile().mkdirs();
            }
            // 假如目标文件不存在,则新建该文件
            if (!file.exists()) {
                logger.info("合成后图片目标文件不存在,新建该文件");
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
            return true;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpPost != null) {
                try {
                    httpPost.clone();
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            }
            if (httpCilent != null) {
                try {
                    httpCilent.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }



}
